#!/bin/csh  -fvx

# To run a coupled HIRHAM-OpenMI session, first modify this script to match
# the OpenMI setup defined, e.g. in the GUI. Then
#
# (1) Start this script in the run directory (e.g. /data/...)
# (2) Submit run.job
# (3) Start the coupled model run from the OpenMI interface, e.g. the GUI
#
# Note: If the script crashes, the data exchange is suspended and 
# model execution is suspended indefinitely.

set nout = 0
set nout_old = 0
set nout_st = 12
set nout_q = ()

set nin = 0
set nin_old = 0
set nin_st = 12
set nin_q = ()

######################################
#
# Define OpenMI interface (user)
#
######################################

## HIRHAM5 model run (should be the same as in run.job), dt (seconds)
set hirham_dt = 120

## OpenMI directory  
# This directory should be visible to Windows/OpenMI, e.g. using SAMBA,
# and allow for file transfer from the run directory
set openmi_remote = mad@ymer
set openmi_localdir = ./openmi
set openmi_dir = $openmi_remote':'$openmi_localdir

## Coupled run mode
# 0 = no coupling
# 1 = 1-way coupling (HIRHAM5 export only)
# 2 = 2-way-coupling
# 3 = 1-way coupling (HIRHAM5 import only, e.g. debugging)
set openmi_mode = 2


## Time stamp for first OpenMI exchange
set openmi_year = 1987
set openmi_month = 5
set openmi_day = 1
set openmi_hour = 0
set openmi_minute = 0
set openmi_second = 0


## Time between subsequent HIRHAM exchanges (import/export, seconds)
# open_acc should be an integer
set openmi_dtin = 3600
set openmi_dtout = 3600

@ openmi_lasto = $openmi_dtout / $hirham_dt
@ openmi_lasti = $openmi_dtin / $hirham_dt

## Define HIRHAM subgrid to exchange (or define full grid)
## Offset to the grid cell in the lower left corner of the domain (openmi_x,openmi_y),
## no. of grid cells in the longitudinal, latitudinal direction (openmi_nlon,openmi_nlat)
set openmi_x = 40
set openmi_y = 64
set openmi_nlon = 3
set openmi_nlat = 3


## OpenMI control files
rm openmi_ini.txt
rm openmi_time.txt

echo $openmi_mode $openmi_year  $openmi_month  $openmi_day  $openmi_hour  $openmi_minute  $openmi_second  $openmi_dtin  $openmi_lasti $openmi_dtout $openmi_lasto $openmi_x $openmi_y $openmi_nlon $openmi_nlat > openmi_ini.txt


## Control semaphores
# if *_data_ready.txt exists it means that the model has produced output that has not yet been 'consumed'
# if openmi_stop.txt exists, it aborts this script
rm hirham_data_ready.txt
rm openmi_data_ready.txt
rm openmi_stop.txt
ssh $openmi_remote 'rm '$openmi_localdir'/openmi_data_ready.txt'
ssh $openmi_remote 'rm '$openmi_localdir'/openmi_stop.txt'
ssh $openmi_remote 'rm '$openmi_localdir'/hirham_data_ready.txt'


## HIRHAM5 input and output fields
set opar = ( hirham ts )
## set ipar = ( ts ahfl )
set ipar = ( ts )

foreach i ( $opar )
    if ( -e $i'.out' ) rm $i'.out'
end

# Special case for FIFE FIXME (remove)
if ( -e sohr.out ) rm sohr.out
if ( -e openmi_nstep.txt) rm openmi_nstep.txt


######################################
#
# INITIALIZATION
#
######################################

set OpenMIDataReady = 0
set HirhamDataReady = 0
set OpenMIStop = 0


######################################
#
# LOOP BEGIN
#
######################################

echo "Begin loop"

loop_begin:

    # get updated OpenMI status information from openmi_dir, i.e. check if the next 
    # OpenMI data input to HIRHAM is ready

## LEGACY - REMOVE EVENTUALLY
## Commented out for now, 25/5, MAD
##    scp $openmi_dir/openmi_data_ready.txt .
##    scp $openmi_dir/openmi_stop.txt .


    # update the control semaphores

    # OpenMIReady can only be signaled by OpenMI
    set tt = `ssh $openmi_remote "cd $openmi_localdir; if (-e openmi_data_ready.txt) echo 1"`
    echo $tt

    if ( $tt == 1 ) then
	set OpenMIDataReady = 1
##	@ nin = $nin + 1
    endif


## LEGACY?
##    if ( -e 'openmi_data_ready.txt' ) set OpenMIDataReady = 1

    # HirhamDataReady can only be signaled by HIRHAM
    # OpenMIStop can only be signaled by HIRHAM, since we want HIRHAM to finish
    # nicely at the end of a month as usual.

    if ( -e 'hirham_data_ready.txt' ) then
	set nout = `cat hirham_data_ready.txt | head -1 | awk '{print $1}'`
	set HirhamDataReady = 1
    endif
    if ( -e 'openmi_stop.txt' ) set OpenMIStop = 1



######################################
#
# STOP THE SCRIPT
#
######################################

    if ( $OpenMIStop == 1 ) then
	goto connection_stop
    endif


######################################
#
# HIRHAM SETVALUES
#
######################################

    if ( $HirhamDataReady == 1 && $nout > $nout_old ) then

    # When HIRHAM has finished producing new data files, it produces a semaphore file
    # 'hirham_data_ready.txt' and then waits. If the file exists, HirhamDataReady is set to 1.

    # Copy semaphore file and data files from the run directory to openmi_dir.
    # This signals to OpenMI that new values are available
 
## (Un)comment the following line for two-way coupled runs 

	foreach i ( $opar )
	    cp $i'.out' $i'.out.'$nout

## Test
	    cp $i'.out' $i'.in'
       
##	    scp $i'.out' $openmi_dir/.

## For debugging only - do not copy data files to the openmi_dir - uncomment the line(s) above
## for two-way coupled runs
	    if ( -e $i'.out' ) rm $i'.out'
	end
	set nout_old = $nout
##       scp hirham_data_ready.txt $openmi_dir/. 

        # Keep a limited number of data files in the run directory for debugging purposes
	set nout_q = ($nout_q $nout)

	if ( $#nout_q > $nout_st ) then
	  foreach i ( $opar ) 
	    rm $i'.out.'$nout_q[1]
	  end
	  shift nout_q
	endif

	# Now the data transfer is complete, so we signal HIRHAM by deleting hirham_data_ready.txt 
        # to resume the run (logging is now done automatically by HIRHAM)
	rm hirham_data_ready.txt

## TEMP
	@ nin = $nin + 1
	echo 0 > openmi_data_ready.txt
	set OpenMIDataReady = 1
    endif


######################################
#
# OPENMI SETVALUES
#
######################################

    if ( $OpenMIDataReady == 1 && $nin > $nin_old ) then

    # When OpenMI has finished producing new data files, it produces a semaphore file
    # 'openmi_data_ready.txt' and then waits. If the file exists, OpenMIDataReady is set to 1.

    # Copy semaphore file and data files to the run directory from openmi_dir.
    # This signals to HIRHAM that new values are available
 
## (Un)comment the following line for two-way coupled runs 

	foreach i ( $ipar )
	    cp $i'.in' $i'.in.'$nin
##	    scp $openmi_dir/$i'.in' .
#	    if ( -e $i'.in' ) rm $i'.in'
	end	
	set nin_old = $nin
##	scp openmi_dir/openmi_data_ready.txt .


        # Keep a limited number of data files in the run directory for debugging purposes
	set nin_q = ($nin_q $nin)

	if ( $#nin_q > $nin_st ) then
	  foreach i ( $ipar ) 
	    rm $i'.in.'$nin_q[1]
          end
	  shift nin_q
	endif

	# Now the data transfer is complete, so we signal OpenMI by deleting openmi_data_ready.txt 
        # to resume the run
##	rm openmi_data_ready.txt
##	ssh $openmi_remote 'rm '$openmi_localdir'/openmi_data_ready.txt'
    endif


## Wait
sleep 1


goto loop_begin

connection_stop:
# end script
